<%@ include file="/WEB-INF/jsp/common/IncludeTop.jsp"%>
<%@page pageEncoding="UTF-8"%>

<!-- <link rel="stylesheet" href="jquery-ui/themes/themes/ui-lightness/jquery-ui.css"> -->
<link href="datepicker/css/datepicker.css" rel="stylesheet"
  type="text/css" />
<link rel="stylesheet" href="zTree/css/zTreeStyle/zTreeStyle.css"
  type="text/css">
<link rel="stylesheet" href="zTree/css/metroStyle/metroStyle.css"
  type="text/css">


<script type="text/javascript"
  src="datepicker/js/bootstrap-datepicker.js"></script>
<script type="text/javascript"
  src="datepicker/js/bootstrap-datepicker.ja.min.js"></script>

<style>
.ui-datepicker {
	font-size: 10px;
}
</style>

<c:if test="${not empty message}">
  <div class="message green">${message}</div>
</c:if>

<div class="col-lg-0 col-lg-offset-0">
  <div class="panel-group" id="accordion">
    <div class="panel panel-primary">
      <div class="panel-heading">
        <h3 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion"
            href="#collapseOne"><spring:message
              code="label.organization" /><span style="float: right;">▼</span></a>
        </h3>
      </div>
      <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">
          <div class="row col-lg-12">
            <form:form id="submitForm" class="form-horizontal"
              method="get" modelAttribute="organization"
              action="organizationInfo.web">
              <fieldset>
                <legend>
                  <spring:message code="label.orgSelect" />
                </legend>

                <!-- 基準日-->
                <div class="form-group">
                  <label for="searchDate" class="col-lg-2 control-label"><spring:message
                      code="label.searchDate" /></label>
                  <div class="date form_date col-lg-5"
                    data-date-viewmode="years">
                    <input path="effStartDate" type="text"
                      class="form-control" id="searchDate"
                      placeholder="<spring:message code="label.searchDate"/>"
                      value="${searchDate}" />
                  </div>
                </div>

                <!-- 取引先会社名 -->
                <div class="form-group">
                  <label for="select" class="col-lg-2 control-label"><spring:message
                      code="label.customername" /></label>
                  <div class="col-lg-5">
                    <select class="form-control" id="selectCustomer">
                      <option value="0" selected>----------</option>
                      <c:forEach items="${customerList}"
                        var="customerList">
                        <option value="${customerList.customercd}">${customerList.customername}</option>
                      </c:forEach>
                    </select>
                  </div>
                </div>

                <!-- 卸会社 -->
                <div class="form-group">
                  <label for="select" class="col-lg-2 control-label"><spring:message
                      code="label.whsName" /></label>
                  <div class="col-lg-5">
                    <select class="form-control" id="selectOrg"
                      path="whsCd">
                      <option value="0" selected>----------</option>
                    </select>
                  </div>
                </div>
              </fieldset>
              <fieldset>
                <div class="form-group">
                  <div class="col-lg-10 col-lg-offset-2">
                    <button type="reset" class="btn btn-default btn-sm">
                      <spring:message code="lable.clear" />
                    </button>
                  </div>
                </div>

              </fieldset>
            </form:form>
          </div>
          <div class="row col-lg-12">
            <!-- テーブル内容 -->
            <div class="well">
              <table class="table table-striped table-hover ">
                <thead>
                  <tr>
                    <th>ユーザー</th>
                    <th>ホールディングス</th>
                    <th>卸会社</th>
                    <th>階層数</th>
                    <th>適用開始日</th>
                    <th>適用終了日</th>
                    <th>組織変更</th>
                  </tr>
                </thead>
                <tbody>
                  <tr class="info" id="tableInfo">
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

        </div>
      </div>
    </div>
    <div id="orgInfo" class="panel panel-primary collapse">
      <div class="panel-body">
        <div class="col-md-12 col-md-offset-0">
          <ul id="orgTree" class="ztree"></ul>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="orgModal" tabindex="-1" role="dialog"
  aria-labelledby="orgInfoModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"
          aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="orgModalLabel">組織詳細</h4>
      </div>

      <div class="modal-body">
        <div class="container-fluid">
          <!-- The async form to send and replace the modals content with its response -->
          <form id="ratting-form" class="form-horizontal well" data-async
            data-target="#orgModal" action="/organizationNode.web"
            method="POST">
            <fieldset>
              <div class="form-group">
                <label class="col-xs-4 control-label for="inputSmall">卸コード</label>
                <div class="col-xs-8">
                  <input class="form-control input-sm" type="text"
                    id="whsCd">
                </div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label for="inputSmall">卸サブコード</label>
                <div class="col-xs-8">
                  <input class="form-control input-sm" type="text"
                    id="whsSubCd">
                </div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label for="inputSmall">卸部署名</label>
                <div class="col-xs-8">
                  <input class="form-control input-sm" type="text"
                    id="whsOrgNm">
                </div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label for="inputSmall">卸組織コード桁区</label>
                <div class="col-xs-8">
                  <input class="form-control input-sm" type="text"
                    id="whsOrgCd">
                </div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label for="inputSmall">組織外部連携コード</label>
                <div class="col-xs-8">
                  <input class="form-control input-sm" type="text"
                    id="whsDepoCd">
                </div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label for="inputSmall">組織外部連携表示順</label>
                <div class="col-xs-8">
                  <input class="form-control input-sm" type="text"
                    id="whsDepoCdSeq">
                </div>
              </div>
            </fieldset>
          </form>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-default"
          data-dismiss="modal">
          <spring:message code="lable.clear" />
        </button>
        <button form="ratting-form" class="btn btn-primary" type="submit"><spring:message code="lable.submit" /></button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<script type="text/javascript">
jQuery(function($) {
    $('form[data-async]').on('submit', function(event) {
        var $form = $(this);
        var $target = $($form.attr('data-target'));

        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),

            success: function(data, status) {
                $target.modal('hide');
            }
        });

        event.preventDefault();
    });
});
//-->
</script>

<script type="text/javascript">
	$(function() {
		$('#searchDate').datepicker({
			format : 'yyyy-mm-dd',
			language : 'ja',
			showWeek : true,
			firstDay : 1,
			autoSize : true
		});

	});
</script>
<script type="text/javascript">
	$(function() {
		$("#selectCustomer").change(
				function() {
					var value = $("#selectCustomer option:selected").val();
					var today = $("#searchDate").val();
					console.log("param: " + value + " | " + today);
					//Ajax
					$.ajax({
						url : 'organizationList.web',
						data : {
							customerCd : value,
							startDate : today
						},
						type : 'GET',
						dataType : 'json',
						success : function(data) {
							success(data);
							$("#selectOrg").html("");
							$("#tableInfo").html("");
							$("#selectOrg").append(
									"<option value="+"0"+" selected>"
											+ "--------" + "</option>");
							for (var i = 0; i < data.length; i++) {
								$("#selectOrg").append(
										"<option value="+data[i].whsCd+">"
												+ data[i].whsNm + "</option>");
							}
						},
						error : function(XMLHttpRequest, textStatus,
								errorThrown) {
							error(XMLHttpRequest, textStatus, errorThrown);
						}
					});

				})
	});

	$(function() {
		$("#selectOrg")
				.change(
						function() {
							var value = $("#selectOrg option:selected").val();
							var today = $("#searchDate").val();
							console.log("param: " + value + " | " + today);
							//Ajax
							$
									.ajax({
										url : 'organizationInfo.web',
										data : {
											whsCd : value,
											startDate : today
										},
										type : 'GET',
										contentType : "application/x-www-form-urlencoded; charset=UTF-8",
										dataType : "json",
										success : function(data) {
											//success(data);
											$("#tableInfo").html("");
											for (var i = 0; i < data.length; i++) {
												$("#tableInfo")
														.append(
																"<td>"
																		+ data[i].customerName
																		+ "</td>"
																		+ "<td>"
																		+ data[i].holdingName
																		+ "</td>"
																		+ "<td>"
																		+ data[i].whsName
																		+ "</td>"
																		+ "<td style=" + "'display: none'" + ">"
																		+ data[i].whsCd
																		+ "</td>"
																		+ "<td>"
																		+ data[i].layer
																		+ "</td>"
																		+ "<td>"
																		+ data[i].startDate
																		+ "</td>"
																		+ "<td>"
																		+ data[i].endDate
																		+ "</td>"
																		+ "<td><button data-toggle='collapse' data-target='#orgInfo' class='btn btn-primary btn-xs' onclick='setWhsCd("
																		+ data[i].whsCd
																		+ "); createTree("
																		+ data[i].whsCd
																		+ ");'>組織変更</button></td>");
											}
										},
										error : function(XMLHttpRequest,
												textStatus, errorThrown) {
											error(XMLHttpRequest, textStatus,
													errorThrown);
										}
									});
						})
	});

	// Ajax通信成功時処理
	function success(data) {
		console.log("data: " + data);
	}

	// Ajax通信失敗時処理
	function error(XMLHttpRequest, textStatus, errorThrown) {
		alert("error:" + XMLHttpRequest);
		alert("status:" + textStatus);
		alert("errorThrown:" + errorThrown);
	}
</script>

<script type="text/javascript">
	var today = new Date();
	var dd = today.getDate();
	var mm = today.getMonth() + 1; //January is 0!
	var yyyy = today.getFullYear();

	if (dd < 10) {
		dd = '0' + dd
	}

	if (mm < 10) {
		mm = '0' + mm
	}

	today = mm + '/' + dd + '/' + yyyy;
	today = yyyy + '/' + mm + '/' + dd;

	var log, className = "dark";
	var treeID = "orgTree";
	var curDragNodes, autoExpandNode;
	var newCount = 1;
	var whscd;

	function setWhsCd(whsCd) {
		console.log("whscd: " + whsCd);
		return whscd = whsCd;
	}

	var setting = {
		async : {
			enable : true,
			type : "get",
			//contentType: "application/json",
			url : 'organizationNode.web',
			autoParam : [ "id", "name", "pId" ],
		//otherParam : [  ]
		},

		check : {//display checkbox / radio ,default:false
			enable : false
		},

		data : {
			simpleData : {
				enable : true,
				idKey : "id",
				pIdKey : "pId",
				rootPId : null
			}
		},

		edit : {
			enable : true,
			editNameSelectAll : true,
			showRemoveBtn : showRemoveBtn,
			showRenameBtn : showRenameBtn,
			removeTitle : "削除",
			renameTitle : "編集",
			drag : {
				autoExpandTrigger : true,
				prev : dropPrev,
				inner : dropInner,
				next : dropNext
			}
		},

		view : {
			addHoverDom : addHoverDom,
			removeHoverDom : removeHoverDom,
			selectedMulti : false
		},

		callback : {
			dblClickExpand : dblClickExpand,

			beforeExpand : beforeExpand,
			onAsyncSuccess : onAsyncSuccess,
			onAsyncError : onAsyncError,

			beforeEditName : beforeEditName,
			beforeRemove : beforeRemove,
			beforeRename : beforeRename,
			onRemove : onRemove,
			onRename : onRename,

			beforeDrag : beforeDrag,
			beforeDrop : beforeDrop,
			beforeDragOpen : beforeDragOpen,
			onDrag : onDrag,
			onDrop : onDrop,
			onExpand : onExpand
		}
	};

	function dblClickExpand(treeId, treeNode) {
		return treeNode.level > 0;
	}

	function beforeEditName(treeId, treeNode) {
		className = (className === "dark" ? "" : "dark");
		var zTree = $.fn.zTree.getZTreeObj(treeID);
		zTree.selectNode(treeNode);
		return confirm(" 下記のノード：-- " + treeNode.name + " を編集しますか？");
	}
	function beforeRemove(treeId, treeNode) {
		className = (className === "dark" ? "" : "dark");
		var zTree = $.fn.zTree.getZTreeObj(treeID);
		zTree.selectNode(treeNode);
		return confirm("下記のノード-- " + treeNode.name + " を削除しますか？");
	}
	function beforeRename(treeId, treeNode, newName, isCancel) {
		className = (className === "dark" ? "" : "dark");
		if (newName.length == 0) {
			alert("ノード名を入力してください。");
			var zTree = $.fn.zTree.getZTreeObj(treeID);
			setTimeout(function() {
				zTree.editName(treeNode)
			}, 10);
			return false;
		}
		return true;
	}
	function onRemove(e, treeId, treeNode) {
		$.ajax({
			url : 'organizationNodeDel.web',
			data : {
				id : treeNode.id
			},
			type : 'POST',
			success : function(data) {
				alert(data);
			}
		});

	}
	function onRename(e, treeId, treeNode, isCancel) {
		var nameBfo = treeNode.name;
		$.ajax({
			url : 'organizationNodeRename.web',
			data : {
				id : treeNode.id,
				name : treeNode.name
			},
			type : 'POST',
			success : function(data) {
				alert("ノード名を「" + treeNode.name + "」に編集しました。 ");
			}
		});

	}

	function showRemoveBtn(treeId, treeNode) {
		//return !treeNode.isFirstNode;
		return true;
	}
	function showRenameBtn(treeId, treeNode) {
		//return !treeNode.isFirstNode;
		return true;
	}

	function dropPrev(treeId, nodes, targetNode) {

		var pNode = targetNode.getParentNode();
		if (pNode && pNode.dropInner === false) {
			return false;
		} else {
			for (var i = 0, l = curDragNodes.length; i < l; i++) {
				var curPNode = curDragNodes[i].getParentNode();
				if (curPNode && curPNode !== targetNode.getParentNode()
						&& curPNode.childOuter === false) {
					return false;
				}
			}
		}
		return true;
	}
	function dropInner(treeId, nodes, targetNode) {

		if (targetNode && targetNode.dropInner === false) {
			return false;
		} else {
			for (var i = 0, l = curDragNodes.length; i < l; i++) {
				if (!targetNode && curDragNodes[i].dropRoot === false) {
					return false;
				} else if (curDragNodes[i].parentTId
						&& curDragNodes[i].getParentNode() !== targetNode
						&& curDragNodes[i].getParentNode().childOuter === false) {
					return false;
				}
			}
		}
		return true;
	}
	function dropNext(treeId, nodes, targetNode) {

		var pNode = targetNode.getParentNode();
		if (pNode && pNode.dropInner === false) {
			return false;
		} else {
			for (var i = 0, l = curDragNodes.length; i < l; i++) {
				var curPNode = curDragNodes[i].getParentNode();
				if (curPNode && curPNode !== targetNode.getParentNode()
						&& curPNode.childOuter === false) {
					return false;
				}
			}
		}
		return true;
	}

	function addHoverDom(treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");

		if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0)
			return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
				+ "' title='追加' onfocus='this.blur();'></span>";
		console.log("addStr: " + addStr);
		sObj.after(addStr);

		var btn = $("#addBtn_" + treeNode.tId);
		if (btn)
			btn.bind("click", function() {
				$('#orgModal').modal('show');

			});

		/* 		if (btn) btn.bind("click", function () {
		 var zTree = $.fn.zTree.getZTreeObj(treeID);
		 zTree.addNodes(treeNode, {
		 id: (100 + newCount), pId: treeNode.id, name: "new node" + newCount
		 });
		 $.ajax({
		 url: '/ZTree/AsyncAddNodes', //url  action是方法的名称
		 data: { id: (100 + newCount), pid: treeNode.id, name: "new node" + newCount },
		 type: 'POST',
		 success: function (data) {
		 //异常完成后，刷新父节点及下面所有子节点
		 zTree.reAsyncChildNodes(treeNode, "refresh");
		 }
		 });
		 newCount++;
		 return false;
		 }); */

	}

	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_" + treeNode.tId).unbind().remove();
	}

	//var zNodes = [];
	//var zTreeObj;

	function createTree(whsCd) {
		console.log("create tree: " + whsCd);
		//zTreeObj = $.fn.zTree.init($("#" + treeID), setting, zNodes);
		$.ajax({
			url : 'organizationNode.web', //url
			data : {
				whsCd : whsCd,
				startDate : today
			},
			type : 'GET',
			timeout : 20000,
			contentType : "application/x-www-form-urlencoded; charset=UTF-8",
			dataType : "text",
			success : function(data) {
				$.fn.zTree.init($("#" + treeID), setting,
						eval('(' + data + ')'));
			},
			error : function(msg) {
				alert(" error！" + msg);
			}
		});
	}

	function beforeExpand(treeId, treeNode) {
		if (!treeNode.isAjaxing) {
			return true;
		} else {
			alert("zTree 展開中。。。");
			return false;
		}
	}
	function onAsyncSuccess(event, treeId, treeNode, msg) {
		/* 	var nodes = treeNode.children;	 
		 var treeObj = $.fn.zTree.getZTreeObj(treeId); 

		 for(var i=0;i<nodes.length;i++){
		 //展開
		 treeObj.expandNode(nodes[i],true,false,true,true);
		 } */
	}
	function onAsyncError() {
		alert(" error");
	}
	function beforeDrag(treeId, treeNodes) {
		className = (className === "dark" ? "" : "dark");
		for (var i = 0, l = treeNodes.length; i < l; i++) {
			if (treeNodes[i].drag === false) {
				curDragNodes = null;
				return false;
			} else if (treeNodes[i].parentTId
					&& treeNodes[i].getParentNode().childDrag === false) {
				curDragNodes = null;
				return false;
			}
		}
		curDragNodes = treeNodes;
		return true;
	}

	function beforeDragOpen(treeId, treeNode) {
		autoExpandNode = treeNode;
		return true;
	}

	function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
		className = (className === "dark" ? "" : "dark");
		return true;
	}

	function onDrag(event, treeId, treeNodes) {
		className = (className === "dark" ? "" : "dark");
	}

	function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
		className = (className === "dark" ? "" : "dark");
		$.ajax({
			url : 'asyncDragNodes.web', // url 
			data : {
				id : treeNodes[0].id,
				pid : targetNode.id,
				name : treeNodes[0].name,
				moveType : moveType,
				isCopy : isCopy
			},
			type : 'POST',
			success : function(data) {
			}
		});

	}

	function onExpand(event, treeId, treeNode) {
		if (treeNode === autoExpandNode) {
			className = (className === "dark" ? "" : "dark");
		}
	}
//-->
</script>

<script type="text/javascript"
  src="zTree/js/jquery.ztree.all-3.5.min.js"></script>
</body>
</html>